package cn.stimd.spring.context.annotation;

import cn.stimd.spring.aop.config.AopConfigUtils;
import cn.stimd.spring.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Set;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar{

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //获取声明的所有注解，形式为全类名数组
        Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
        for (String annType : annTypes) {
            //获取某个注解的所有属性值
            AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
            if (candidate == null) {
                continue;
            }

            //获取@EnableTransactionManagement注解的属性
            Object mode = candidate.get("mode");
            Object proxyTargetClass = candidate.get("proxyTargetClass");

            if (mode == AdviceMode.PROXY) {
                //注册InfrastructureAdvisorAutoProxyCreator
                AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);

                //如果proxyTargetClass为true，即使用Cglib创建代理对象，则需要修改属性
                if((Boolean)proxyTargetClass){
                    AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
                }
            }
        }
    }
}
